package stu.aistar.controller;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import stu.aistar.dao.IMovieDao;
import stu.aistar.model.pojo.Orders;
import stu.aistar.service.IOrdersService;
import stu.aistar.util.MatrixToImageWriterEx;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Controller
@RequestMapping("/Qrcode")
public class QrcodeGeneratorController {
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IMovieDao movieDao;
    /**
     *
     * @param
     * @return
     */
    @GetMapping("/sendcode")
    @ResponseBody
    public String encode(String content) {
        try {
            String base64;
            BitMatrix matrix = MatrixToImageWriterEx.createQRCode(content, 300, 300);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);
            System.out.println(image);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            base64 = "data:image/jpeg;base64,"+Base64.encode(stream.toByteArray());
            System.out.println(base64);
            return base64;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @GetMapping("showcode")
    public String showcode(Model model,String ordersNo,String ordersImg){
        Orders orders=ordersService.findOrdersByOrdersNo(ordersNo);
        System.out.println(orders);
        String content=orders.getMovieName()+orders.getOrdersNo()+orders.getSeats()+orders.getTotal();
        model.addAttribute("qrcode",encode(content));
        model.addAttribute("orders",orders);
        model.addAttribute("ordersImg",ordersImg);
        System.out.println("ordersImg:"+ordersImg);
        return "qrcode";
    }

}
